#!/usr/bin/env python
# -*- coding: utf-8 -*-

import sys
import wx
import os
import webbrowser
sys.path.append("../Controller")
sys.path.append("../Image")
from view_file_chooser import CLS_View_File_Chooser
from cont_read_xls import CLS_Contlr_Read_Xls
from cont_insert_bdd import CLS_Contlr_Insert_Bdd
from cont_queries import CLS_Contlr_Queries
from cont_write_csv import CLS_Contlr_Write_Csv
from cont_plot_img import CLS_Contlr_App_Plot
from cont_system_info import CLS_Contlr_System_Info
import profile
import time

FINAL_NAME_BDD = "Inscritos_2010-2011-bdd.db"
APP_EXIT = 1


class CLS_Main_Frame(wx.Frame):

    '''
    CLS_Main_Frame -> Frame principal

    Janela principal, frame, painel e sizer.
    '''

    def __init__(self, *args, **kwds):

        ''' ARGV -> Self wx.Frame '''

        if (os.path.exists('Data/testes.txt')):
            os.unlink('Data/testes.txt')

        kwds["style"] = wx.DEFAULT_FRAME_STYLE  ^  (wx.RESIZE_BORDER | wx.MINIMIZE_BOX | wx.MAXIMIZE_BOX)
        wx.Frame.__init__(self, *args, **kwds)
        
        # Menu Bar
        self.frameMain_menubar = wx.MenuBar()
        self.file_m = wx.Menu()
        self.open_m = wx.MenuItem(self.file_m, wx.NewId(), "&Abrir xls", "", wx.ITEM_NORMAL)
        self.file_m.AppendItem(self.open_m)
        self.savebdd_m = wx.MenuItem(self.file_m, wx.NewId(), "&Gravar xls -> bdd", "", wx.ITEM_NORMAL)
        self.file_m.AppendItem(self.savebdd_m)
        self.exit_m = wx.MenuItem(self.file_m, wx.NewId(), "&Sair", "", wx.ITEM_NORMAL)
        self.exit_m.SetBitmap(wx.Bitmap('Image/img_close_15.png'))
        self.file_m.AppendItem(self.exit_m)
        self.frameMain_menubar.Append(self.file_m, "&Ficheiro")
        
        self.stats_m = wx.Menu()
        self.exequery_m = wx.MenuItem(self.stats_m, wx.NewId(), "Executar queries", "", wx.ITEM_NORMAL)
        self.stats_m.AppendItem(self.exequery_m)
        self.savecsv_m = wx.MenuItem(self.stats_m, wx.NewId(), "Guardar para csv", "", wx.ITEM_NORMAL)
        self.stats_m.AppendItem(self.savecsv_m)
        self.viewgraph_m = wx.MenuItem(self.stats_m, wx.NewId(), u"Ver gráficos", "", wx.ITEM_NORMAL)
        self.stats_m.AppendItem(self.viewgraph_m)
        self.frameMain_menubar.Append(self.stats_m, u"&Estatísticas")
        
        self.help_m = wx.Menu()
        self.help_subm = wx.MenuItem(self.help_m, wx.NewId(), "Ajuda", "", wx.ITEM_NORMAL)
        self.help_m.AppendItem(self.help_subm)
        self.about_m = wx.MenuItem(self.help_m, wx.NewId(), "Sobre Sistema", "", wx.ITEM_NORMAL)
        self.help_m.AppendItem(self.about_m)
        self.frameMain_menubar.Append(self.help_m, "&Ajuda")
        self.SetMenuBar(self.frameMain_menubar)
        
        self.SetMenuBar(self.frameMain_menubar)
        
        # Tool Bar
        self.frameMain_toolbar = wx.ToolBar(self, -1)
        self.SetToolBar(self.frameMain_toolbar)
        # Tool Bar end
        
        self.frameMain_statusbar = self.CreateStatusBar(1, 0)
        # Painel inicial
        self.panelHome_1 = wx.Panel(self, -1)
        self.textPanelHome_1 = wx.StaticText(self.panelHome_1, -1, "\nFunções :\n\n\nEscolha do ficheiro Excell\nImportação para BDD SqLite3\nGravação de pedidos em CSV\nIlustracao gráfica\nTestes execução\nRelatório PDF\n\n\n\nContinuar ?", style=wx.ALIGN_CENTRE)
        self.sizerPanelHome_1_staticbox = wx.StaticBox(self.panelHome_1, -1, "   Bem-vindo(a)   ")
        # Painel abrir xls
        self.panelXls_2 = wx.Panel(self, -1)
        self.txtPanelXls_2_1 = wx.StaticText(self.panelXls_2, -1, "\nSelecione o ficheiro Excel...")
        self.imgPanelXls_2 = wx.BitmapButton(self.panelXls_2, -1, wx.Bitmap("Image/excel_40.png", wx.BITMAP_TYPE_ANY))
        self.txtPanelXls_2_2 = wx.StaticText(self.panelXls_2, -1, "\n\nNome do ficheiro :")
        self.txtPanelXls_2_3 = wx.StaticText(self.panelXls_2, -1, " ")
        self.txtPanelXls_2_4 = wx.StaticText(self.panelXls_2, -1, "\n\nContinuar e importar para a BDD ?\n", style=wx.ALIGN_CENTRE)
        self.sizerPanelXls_2_staticbox = wx.StaticBox(self.panelXls_2, -1, "   Importação - XLS   ")
        # Painel gravar bdd
        self.panelBdd_3 = wx.Panel(self, -1)
        self.txtPanelBdd_3_1 = wx.StaticText(self.panelBdd_3, -1, "\nCriação da BDD")
        self.imgPanelBdd_3 = wx.BitmapButton(self.panelBdd_3, -1, wx.Bitmap("Image/bdd_40.png", wx.BITMAP_TYPE_ANY))
        self.txtPanelBdd_3_2 = wx.StaticText(self.panelBdd_3, -1, "\n\nNome do ficheiro :")
        self.txtPanelBdd_3_3 = wx.StaticText(self.panelBdd_3, -1, "")
        self.txtPanelBdd_3_4 = wx.StaticText(self.panelBdd_3, -1, "\n\nContinuar e importar estatisticas em CSV ?\n", style=wx.ALIGN_CENTRE)
        self.sizerPanelBdd_3_staticbox = wx.StaticBox(self.panelBdd_3, -1, "   Importação - BDD   ")
        # Painel gravar estatisticas
        self.panelCSV_4 = wx.Panel(self, -1)
        self.txtPanelCSV_4_2 = wx.StaticText(self.panelCSV_4, -1, "\nCursos - Computadores e Informática\n\nAlunos / Nível / Ano\nEstabelecimento / Unidade orgânica / Anos letivos\nAlunos / Curso / Ano\n", style=wx.ALIGN_CENTRE)
        self.imgPanelCSV_4 = wx.BitmapButton(self.panelCSV_4, -1, wx.Bitmap("Image/csv_40.png", wx.BITMAP_TYPE_ANY))
        self.txtPanelCSV_4_5 = wx.StaticText(self.panelCSV_4, -1, "\nNome do ficheiro :") #, style=wx.ALIGN_CENTRE
        self.sizerPanelCSV_4_staticbox = wx.StaticBox(self.panelCSV_4, -1, "   Exportação - CSV   ")
        self.imgPanelCSV_4.SetBackgroundColour(wx.Colour(255, 255, 255))
        self.imgPanelCSV_4.SetSize(self.imgPanelCSV_4.GetBestSize())
        self.panelCSV_4.SetBackgroundColour(wx.Colour(255, 255, 255))
        # Painel ver graficos
        self.panelPlot_5 = wx.Panel(self, -1)
        self.txtPanelPlot_5_1 = wx.StaticText(self.panelPlot_5, -1, "\nInformática - Computadores")
        self.txtPanelPlot_5_2 = wx.StaticText(self.panelPlot_5, -1, "\nPor curso :")
        self.comboPanelPlot_5_1 = wx.ComboBox(self.panelPlot_5, -1, choices=[], style=wx.CB_DROPDOWN)
        self.comboPanelPlot_5_2 = wx.ComboBox(self.panelPlot_5, -1, choices=[], style=wx.CB_DROPDOWN | wx.CB_SIMPLE | wx.CB_DROPDOWN)
        self.imgPanelPlot_5_1 = wx.BitmapButton(self.panelPlot_5, -1, wx.Bitmap("Image/plot_30.png", wx.BITMAP_TYPE_ANY))
        self.txtPanelPlot_5_3 = wx.StaticText(self.panelPlot_5, -1, "Por nível :")
        self.comboPanelPlot_5_3 = wx.ComboBox(self.panelPlot_5, -1, choices=[], style=wx.CB_DROPDOWN)
        self.comboPanelPlot_5_4 = wx.ComboBox(self.panelPlot_5, -1, choices=[], style=wx.CB_DROPDOWN)
        self.imgPanelPlot_5_2 = wx.BitmapButton(self.panelPlot_5, -1, wx.Bitmap("Image/plot_30.png", wx.BITMAP_TYPE_ANY))
        self.txtPanelPlot_5_4 = wx.StaticText(self.panelPlot_5, -1, "\nVisualisar dados finais ?\n")
        self.sizerPanelPlot_5_staticbox = wx.StaticBox(self.panelPlot_5, -1, "   Estatisticas - Graficos   ")
        # Painel final
        self.panelFinal_6 = wx.Panel(self, -1)
        self.imgPanelFinal_6_1 = wx.BitmapButton(self.panelFinal_6, -1, wx.Bitmap("Image/excel_30.png", wx.BITMAP_TYPE_ANY))
        self.txtPanelFinal_6_1 = wx.StaticText(self.panelFinal_6, -1, "   Abrir ficheiro analisado")
        self.imgPanelFinal_6_2 = wx.BitmapButton(self.panelFinal_6, -1, wx.Bitmap("Image/bdd_30.png", wx.BITMAP_TYPE_ANY))
        self.txtPanelFinal_6_2 = wx.StaticText(self.panelFinal_6, -1, "   Abrir a BDD - SqLite3")
        self.imgPanelFinal_6_3 = wx.BitmapButton(self.panelFinal_6, -1, wx.Bitmap("Image/csv_30.png", wx.BITMAP_TYPE_ANY))
        self.txtPanelFinal_6_3 = wx.StaticText(self.panelFinal_6, -1, "   Abrir estatísticas em CSV")
        self.imgPanelFinal_6_4 = wx.BitmapButton(self.panelFinal_6, -1, wx.Bitmap("Image/plot_30.png", wx.BITMAP_TYPE_ANY))
        self.txtPanelFinal_6_4 = wx.StaticText(self.panelFinal_6, -1, "   Gráficos das estatísticas")
        self.imgPanelFinal_6_5 = wx.BitmapButton(self.panelFinal_6, -1, wx.Bitmap("Image/pdf_30.png", wx.BITMAP_TYPE_ANY))
        self.txtPanelFinal_6_5 = wx.StaticText(self.panelFinal_6, -1, "   Testes de execuçãoo")
        self.imgPanelFinal_6_6 = wx.BitmapButton(self.panelFinal_6, -1, wx.Bitmap("Image/testes_30.png", wx.BITMAP_TYPE_ANY))
        self.txtPanelFinal_6_6 = wx.StaticText(self.panelFinal_6, -1, "   Relatório PDF")
        self.sizerPanelFinal_6_staticbox = wx.StaticBox(self.panelFinal_6, -1, "   FINAL   ")
        # Painel botoes sair e continuar
        self.panelOnOff = wx.Panel(self, -1)
        self.imgPanelOnOff_1 = wx.BitmapButton(self.panelOnOff, -1, wx.Bitmap("Image/img_close.png", wx.BITMAP_TYPE_ANY))
        self.imgPanelOnOff_2 = wx.BitmapButton(self.panelOnOff, -1, wx.Bitmap("Image/img_next.png", wx.BITMAP_TYPE_ANY))

		# Bind
        self.Bind(wx.EVT_BUTTON, self.evtOpenXls, self.imgPanelXls_2)
        self.Bind(wx.EVT_MENU, self.evtOpenXls, self.open_m)
        self.Bind(wx.EVT_BUTTON, self.evtSaveBdd, self.imgPanelBdd_3)
        self.Bind(wx.EVT_MENU, self.evtSaveBdd, self.savebdd_m)
        self.Bind(wx.EVT_BUTTON, self.evtToCsv, self.imgPanelCSV_4)
        self.Bind(wx.EVT_MENU, self.evtMenuSaveCsv, self.savecsv_m)
        self.Bind(wx.EVT_MENU, self.evtMenuShowGraph, self.viewgraph_m)
        self.Bind(wx.EVT_MENU, self.evtMenuSystemInfo, self.about_m)
        self.Bind(wx.EVT_BUTTON, self.evtInfoXls, self.imgPanelFinal_6_1)
        self.Bind(wx.EVT_BUTTON, self.evtInfoBdd, self.imgPanelFinal_6_2)
        self.Bind(wx.EVT_BUTTON, self.evtInfoCsv, self.imgPanelFinal_6_3)
        self.Bind(wx.EVT_BUTTON, self.evtMenuShowGraph, self.imgPanelFinal_6_4)
        self.Bind(wx.EVT_BUTTON, self.evtInfoTeste, self.imgPanelFinal_6_5)
        self.Bind(wx.EVT_BUTTON, self.evtInfoPdf, self.imgPanelFinal_6_6)
        self.Bind(wx.EVT_BUTTON, self.evtClose, self.imgPanelOnOff_1)
        self.Bind(wx.EVT_MENU, self.evtClose, self.exit_m)
        self.Bind(wx.EVT_BUTTON, self.evtNext, self.imgPanelOnOff_2)
        # Eventos botao e comboboxs para ver grafico alunos por curso
        self.Bind(wx.EVT_BUTTON, self.ongrafico_curso, self.imgPanelPlot_5_1)
        self.Bind(wx.EVT_COMBOBOX, self.oncombo_unidade_curso, self.comboPanelPlot_5_1)
        self.Bind(wx.EVT_COMBOBOX, self.oncombo_curso, self.comboPanelPlot_5_2)
        # Eventos botao e comboboxs para ver grafico alunos por nivel
        self.Bind(wx.EVT_BUTTON, self.ongrafico_nivel, self.imgPanelPlot_5_2)
        self.Bind(wx.EVT_COMBOBOX, self.oncombo_unidade_nivel, self.comboPanelPlot_5_3)
        self.Bind(wx.EVT_COMBOBOX, self.oncombo_nivel, self.comboPanelPlot_5_4)
        
        self.file_chooser = CLS_View_File_Chooser()
        self.read_xls = CLS_Contlr_Read_Xls()
        self.stats = CLS_Contlr_Queries()

        self.__set_properties()
        self.__do_layout()
		# end wxGlade

    def __set_properties(self):
        
        ''' Propriedades Frame Principal '''

        self.SetTitle(" Análise de Inscrições ")
        _icon = wx.EmptyIcon()
        _icon.CopyFromBitmap(wx.Bitmap("Image/sun.ico", wx.BITMAP_TYPE_ANY))
        self.SetIcon(_icon)
        self.SetSize((410, 410))
        self.SetBackgroundColour(wx.Colour(255, 255, 255))
        
        # Menu options
        self.open_m.Enable(False)
        self.savebdd_m.Enable(False)
        self.exequery_m.Enable(False)
        self.savecsv_m.Enable(False)
        self.viewgraph_m.Enable(False)
        self.frameMain_statusbar.SetStatusWidths([-1])
        
        # statusbar fields
        frameMain_statusbar_fields = ["6311 - Miguel Silva, 6208 - João Luís, ESTIG LP 2012 / 2013"]
        for i in range(len(frameMain_statusbar_fields)):
            self.frameMain_statusbar.SetStatusText(frameMain_statusbar_fields[i], i)
        
        self.panelHome_1.SetBackgroundColour(wx.Colour(255, 255, 255))
        
        self.imgPanelXls_2.SetToolTip(wx.ToolTip("Abrir XLS"))
        self.imgPanelXls_2.SetSize(self.imgPanelXls_2.GetBestSize())
        self.txtPanelXls_2_4.Enable(False)
        self.panelXls_2.SetBackgroundColour(wx.Colour(255, 255, 255))
        self.panelXls_2.Hide()
        
        self.imgPanelBdd_3.SetToolTip(wx.ToolTip("Gravar xls para BDD"))
        self.txtPanelBdd_3_4.Enable(False)
        self.panelBdd_3.SetBackgroundColour(wx.Colour(255, 255, 255))
        self.panelBdd_3.Hide()
        
        self.imgPanelCSV_4.SetToolTip(wx.ToolTip("Gravar CSV"))
        self.panelCSV_4.SetBackgroundColour(wx.Colour(255, 255, 255))
        self.panelCSV_4.Hide()
       
        self.comboPanelPlot_5_1.SetMinSize((150, 30))
        self.comboPanelPlot_5_1.SetSelection(-1)
        self.comboPanelPlot_5_1.SetToolTip(wx.ToolTip("Escolher Unidade Orgânica"))
        self.comboPanelPlot_5_2.SetMinSize((150, 30))
        self.comboPanelPlot_5_2.SetSelection(-1)
        self.comboPanelPlot_5_2.SetToolTip(wx.ToolTip("Escolher Curso"))
        self.imgPanelPlot_5_1.SetToolTipString("Ver Gráfico")
        self.imgPanelPlot_5_1.SetSize(self.imgPanelPlot_5_1.GetBestSize())
        self.imgPanelPlot_5_1.Enable(False)
        self.comboPanelPlot_5_3.SetMinSize((150, 30))
        self.comboPanelPlot_5_3.SetSelection(-1)
        self.comboPanelPlot_5_3.SetToolTip(wx.ToolTip("Escolher Unidade Orgânica"))
        self.comboPanelPlot_5_4.SetMinSize((150, 30))
        self.comboPanelPlot_5_4.SetSelection(-1)
        self.comboPanelPlot_5_4.SetToolTip(wx.ToolTip("Escolher Nível"))
        self.imgPanelPlot_5_2.SetToolTipString("Ver Gráfico")
        self.imgPanelPlot_5_2.SetSize(self.imgPanelPlot_5_2.GetBestSize())
        self.imgPanelPlot_5_2.Enable(False)
        self.panelPlot_5.SetBackgroundColour(wx.Colour(255, 255, 255))
        self.panelPlot_5.Hide()
        
        self.imgPanelFinal_6_1.SetToolTipString("Abrir ficheiro XLS")
        self.imgPanelFinal_6_1.SetSize(self.imgPanelFinal_6_1.GetBestSize())
        self.imgPanelFinal_6_2.SetToolTipString("Abrir BDD SqiLite3")
        self.imgPanelFinal_6_2.SetSize(self.imgPanelFinal_6_2.GetBestSize())
        self.imgPanelFinal_6_3.SetToolTipString("Abrir ficheiro CSV")
        self.imgPanelFinal_6_3.SetSize(self.imgPanelFinal_6_3.GetBestSize())
        self.imgPanelFinal_6_4.SetToolTipString("Voltar aos gráficos")
        self.imgPanelFinal_6_4.SetSize(self.imgPanelFinal_6_4.GetBestSize())
        self.imgPanelFinal_6_5.SetToolTipString("Abrir resultados")
        self.imgPanelFinal_6_5.SetSize(self.imgPanelFinal_6_5.GetBestSize())
        self.imgPanelFinal_6_6.SetToolTipString("Abrir relatório aplicação")
        self.imgPanelFinal_6_6.SetSize(self.imgPanelFinal_6_6.GetBestSize())
        self.panelFinal_6.SetBackgroundColour(wx.Colour(255, 255, 255))
        self.panelFinal_6.Hide()
        
        self.imgPanelOnOff_1.SetBackgroundColour(wx.Colour(243, 243, 243))
        self.imgPanelOnOff_1.SetToolTipString("Fechar aplicação ?")
        self.imgPanelOnOff_1.SetSize(self.imgPanelOnOff_1.GetBestSize())
        self.imgPanelOnOff_2.SetBackgroundColour(wx.Colour(243, 243, 243))
        self.imgPanelOnOff_2.SetToolTipString("Continuar ?")
        self.imgPanelOnOff_2.SetSize(self.imgPanelOnOff_2.GetBestSize())
        self.panelOnOff.SetBackgroundColour(wx.Colour(255, 255, 255))
        # end wxGlade

    def __do_layout(self):

        ''' Propriedades Frame Principal '''

        sizerFrameMain = wx.BoxSizer(wx.VERTICAL)
        sizerPanelOnOff = wx.GridSizer(1, 2, 0, 0)
        self.sizerPanelFinal_6_staticbox.Lower()
        sizerPanelFinal_6 = wx.StaticBoxSizer(self.sizerPanelFinal_6_staticbox, wx.VERTICAL)
        gridPanelFinal_6 = wx.FlexGridSizer(6, 2, 2, 2)
        self.sizerPanelPlot_5_staticbox.Lower()
        sizerPanelPlot_5 = wx.StaticBoxSizer(self.sizerPanelPlot_5_staticbox, wx.VERTICAL)
        gridPanelPlot_5_2 = wx.FlexGridSizer(1, 3, 0, 0)
        gridPanelPlot_5_1 = wx.FlexGridSizer(1, 3, 0, 0)
        self.sizerPanelCSV_4_staticbox.Lower()
        sizerPanelCSV_4 = wx.StaticBoxSizer(self.sizerPanelCSV_4_staticbox, wx.HORIZONTAL)
        gridPanelCSV_4 = wx.FlexGridSizer(1, 1, 0, 0)
        self.sizerPanelBdd_3_staticbox.Lower()
        sizerPanelBdd_3 = wx.StaticBoxSizer(self.sizerPanelBdd_3_staticbox, wx.HORIZONTAL)
        gridPanelBdd_3 = wx.FlexGridSizer(1, 1, 0, 0)
        self.sizerPanelXls_2_staticbox.Lower()
        sizerPanelXls_2 = wx.StaticBoxSizer(self.sizerPanelXls_2_staticbox, wx.HORIZONTAL)
        gridPanelXls_2 = wx.FlexGridSizer(1, 1, 0, 0)
        self.sizerPanelHome_1_staticbox.Lower()
        sizerPanelHome_1 = wx.StaticBoxSizer(self.sizerPanelHome_1_staticbox, wx.HORIZONTAL)
        gridPanelHome_1 = wx.FlexGridSizer(1, 1, 0, 0)
        gridPanelHome_1.Add(self.textPanelHome_1, 0, wx.ALIGN_CENTER_HORIZONTAL, 3)
        gridPanelHome_1.AddGrowableRow(0)
        gridPanelHome_1.AddGrowableCol(0)
        sizerPanelHome_1.Add(gridPanelHome_1, 1, wx.EXPAND, 0)
        self.panelHome_1.SetSizer(sizerPanelHome_1)
        sizerFrameMain.Add(self.panelHome_1, 3, wx.ALL | wx.EXPAND, 4)
        
        gridPanelXls_2.Add(self.txtPanelXls_2_1, 1, wx.ALIGN_CENTER_HORIZONTAL, 0)
        gridPanelXls_2.Add(self.imgPanelXls_2, 1, wx.ALIGN_CENTER_HORIZONTAL, 0)
        gridPanelXls_2.Add(self.txtPanelXls_2_2, 1, wx.ALIGN_CENTER_HORIZONTAL, 0)
        gridPanelXls_2.Add(self.txtPanelXls_2_3, 1, wx.ALIGN_CENTER_HORIZONTAL, 0)
        gridPanelXls_2.Add(self.txtPanelXls_2_4, 1, wx.ALIGN_CENTER_HORIZONTAL | wx.FIXED_MINSIZE, 3)
        gridPanelXls_2.AddGrowableRow(0)
        gridPanelXls_2.AddGrowableCol(0)
        sizerPanelXls_2.Add(gridPanelXls_2, 1, wx.EXPAND, 0)
        self.panelXls_2.SetSizer(sizerPanelXls_2)
        sizerFrameMain.Add(self.panelXls_2, 3, wx.ALL | wx.EXPAND, 4)
        
        gridPanelBdd_3.Add(self.txtPanelBdd_3_1, 1, wx.ALIGN_CENTER_HORIZONTAL, 0)
        gridPanelBdd_3.Add(self.imgPanelBdd_3, 1, wx.ALIGN_CENTER_HORIZONTAL, 0)
        gridPanelBdd_3.Add(self.txtPanelBdd_3_2, 1, wx.ALIGN_CENTER_HORIZONTAL, 0)
        gridPanelBdd_3.Add(self.txtPanelBdd_3_3, 1, wx.ALIGN_CENTER_HORIZONTAL, 0)
        gridPanelBdd_3.Add(self.txtPanelBdd_3_4, 1, wx.ALIGN_CENTER_HORIZONTAL | wx.FIXED_MINSIZE, 3)
        gridPanelBdd_3.AddGrowableRow(0)
        gridPanelBdd_3.AddGrowableCol(0)
        sizerPanelBdd_3.Add(gridPanelBdd_3, 1, wx.EXPAND, 0)
        self.panelBdd_3.SetSizer(sizerPanelBdd_3)
        sizerFrameMain.Add(self.panelBdd_3, 3, wx.ALL | wx.EXPAND, 4)
        
        self.sizerPanelCSV_4_staticbox.Lower()
        sizerPanelCSV_4 = wx.StaticBoxSizer(self.sizerPanelCSV_4_staticbox, wx.HORIZONTAL)
        gridPanelCSV_4 = wx.FlexGridSizer(1, 1, 0, 0)
        gridPanelCSV_4.Add(self.txtPanelCSV_4_2, 1, wx.ALIGN_CENTER_HORIZONTAL, 0)
        gridPanelCSV_4.Add(self.imgPanelCSV_4, 1, wx.ALIGN_CENTER_HORIZONTAL, 0)
        gridPanelCSV_4.Add(self.txtPanelCSV_4_5, 1, wx.ALIGN_CENTER_HORIZONTAL, 0)
        self.txtPanelCSV_4_7 = wx.StaticText(self.panelCSV_4, -1, "\n\nContinuar e visualizar os gráficos ?\n", style=wx.ALIGN_CENTRE)
        self.txtPanelCSV_4_7.Enable(False)
        gridPanelCSV_4.Add(self.txtPanelCSV_4_7, 1, wx.ALIGN_CENTER_HORIZONTAL, 0)
        gridPanelCSV_4.AddGrowableRow(0)
        gridPanelCSV_4.AddGrowableCol(0)
        sizerPanelCSV_4.Add(gridPanelCSV_4, 1, 0, 0)
        self.panelCSV_4.SetSizer(sizerPanelCSV_4)
        sizerFrameMain.Add(self.panelCSV_4, 3, wx.ALL|wx.EXPAND, 4)
        
        sizerPanelPlot_5.Add(self.txtPanelPlot_5_1, 0, wx.ALIGN_CENTER_HORIZONTAL, 0)
        sizerPanelPlot_5.Add(self.txtPanelPlot_5_2, 0, 0, 0)
        gridPanelPlot_5_1.Add(self.comboPanelPlot_5_1, 0, wx.ALIGN_CENTER_VERTICAL, 0)
        gridPanelPlot_5_1.Add(self.comboPanelPlot_5_2, 0, wx.ALIGN_CENTER_VERTICAL, 0)
        gridPanelPlot_5_1.Add(self.imgPanelPlot_5_1, 0, wx.ALIGN_CENTER_HORIZONTAL | wx.ALIGN_CENTER_VERTICAL, 0)
        gridPanelPlot_5_1.AddGrowableRow(0)
        gridPanelPlot_5_1.AddGrowableCol(0)
        gridPanelPlot_5_1.AddGrowableCol(1)
        gridPanelPlot_5_1.AddGrowableCol(2)
        sizerPanelPlot_5.Add(gridPanelPlot_5_1, 1, wx.EXPAND, 0)
        sizerPanelPlot_5.Add(self.txtPanelPlot_5_3, 0, 0, 0)
        gridPanelPlot_5_2.Add(self.comboPanelPlot_5_3, 0, wx.ALIGN_CENTER_VERTICAL, 0)
        gridPanelPlot_5_2.Add(self.comboPanelPlot_5_4, 0, wx.ALIGN_CENTER_VERTICAL, 0)
        gridPanelPlot_5_2.Add(self.imgPanelPlot_5_2, 0, wx.ALIGN_CENTER_HORIZONTAL | wx.ALIGN_CENTER_VERTICAL, 0)
        gridPanelPlot_5_2.AddGrowableRow(0)
        gridPanelPlot_5_2.AddGrowableCol(0)
        gridPanelPlot_5_2.AddGrowableCol(1)
        gridPanelPlot_5_2.AddGrowableCol(2)
        sizerPanelPlot_5.Add(gridPanelPlot_5_2, 1, wx.EXPAND, 0)
        sizerPanelPlot_5.Add(self.txtPanelPlot_5_4, 0, wx.ALIGN_CENTER_HORIZONTAL, 0)
        self.panelPlot_5.SetSizer(sizerPanelPlot_5)
        sizerFrameMain.Add(self.panelPlot_5, 3, wx.ALL | wx.EXPAND, 4)
        gridPanelFinal_6.Add(self.imgPanelFinal_6_1, 0, wx.ALIGN_RIGHT | wx.ALIGN_CENTER_VERTICAL, 0)
        gridPanelFinal_6.Add(self.txtPanelFinal_6_1, 0, wx.ALIGN_CENTER_VERTICAL, 0)
        gridPanelFinal_6.Add(self.imgPanelFinal_6_2, 0, wx.ALIGN_RIGHT | wx.ALIGN_CENTER_VERTICAL, 0)
        gridPanelFinal_6.Add(self.txtPanelFinal_6_2, 0, wx.ALIGN_CENTER_VERTICAL, 0)
        gridPanelFinal_6.Add(self.imgPanelFinal_6_3, 0, wx.ALIGN_RIGHT | wx.ALIGN_CENTER_VERTICAL, 0)
        gridPanelFinal_6.Add(self.txtPanelFinal_6_3, 0, wx.ALIGN_CENTER_VERTICAL, 0)
        gridPanelFinal_6.Add(self.imgPanelFinal_6_4, 0, wx.ALIGN_RIGHT | wx.ALIGN_CENTER_VERTICAL, 0)
        gridPanelFinal_6.Add(self.txtPanelFinal_6_4, 0, wx.ALIGN_CENTER_VERTICAL, 0)
        gridPanelFinal_6.Add(self.imgPanelFinal_6_5, 0, wx.ALIGN_RIGHT | wx.ALIGN_CENTER_VERTICAL, 0)
        gridPanelFinal_6.Add(self.txtPanelFinal_6_5, 0, wx.ALIGN_CENTER_VERTICAL, 0)
        gridPanelFinal_6.Add(self.imgPanelFinal_6_6, 0, wx.ALIGN_RIGHT | wx.ALIGN_CENTER_VERTICAL, 0)
        gridPanelFinal_6.Add(self.txtPanelFinal_6_6, 0, wx.ALIGN_CENTER_VERTICAL, 0)
        gridPanelFinal_6.AddGrowableRow(0)
        gridPanelFinal_6.AddGrowableRow(1)
        gridPanelFinal_6.AddGrowableRow(2)
        gridPanelFinal_6.AddGrowableRow(3)
        gridPanelFinal_6.AddGrowableRow(4)
        gridPanelFinal_6.AddGrowableRow(5)
        gridPanelFinal_6.AddGrowableCol(0)
        gridPanelFinal_6.AddGrowableCol(1)
        sizerPanelFinal_6.Add(gridPanelFinal_6, 1, wx.EXPAND | wx.ALIGN_CENTER_HORIZONTAL, 0)
        self.panelFinal_6.SetSizer(sizerPanelFinal_6)
        sizerFrameMain.Add(self.panelFinal_6, 3, wx.ALL | wx.EXPAND, 4)
        sizerPanelOnOff.Add(self.imgPanelOnOff_1, 0, wx.EXPAND | wx.ALIGN_CENTER_HORIZONTAL | wx.ALIGN_CENTER_VERTICAL, 0)
        sizerPanelOnOff.Add(self.imgPanelOnOff_2, 0, wx.EXPAND | wx.ALIGN_CENTER_HORIZONTAL | wx.ALIGN_CENTER_VERTICAL, 0)
        self.panelOnOff.SetSizer(sizerPanelOnOff)
        sizerFrameMain.Add(self.panelOnOff, 0, wx.ALL | wx.EXPAND, 4)
        self.SetSizer(sizerFrameMain)
        self.Layout()
        # end wxGlade
    
    
    def evtMenuSystemInfo(self, event):
		
		''' Evento -> Informação sobre versão e compilador do Python e, sobre o sistema em que esta a correr '''
		
		system_info = CLS_Contlr_System_Info().get_system_info()
		
		info = wx.AboutDialogInfo()

        #info.SetIcon(wx.Icon('hunter.png', wx.BITMAP_TYPE_PNG))
		info.SetName('Sistema')
		#info.SetVersion('1.0')
		info.SetDescription(system_info)
		info.SetCopyright('(C) 2012 - 2013 João Luís, Miguel Silva')
		#info.SetWebSite('http://www.zetcode.com')
		#info.SetLicence(licence)
		#info.AddDeveloper('Jan Bodnar')
		#info.AddDocWriter('Jan Bodnar')
		#info.AddArtist('The Tango crew')
		#info.AddTranslator('Jan Bodnar')
		wx.AboutBox(info)
    
    def evtMenuShowGraph(self, event):
		
		''' Event -> Menu Show Gráfico '''
        
		if self.panelBdd_3.IsShown():
			self.panelBdd_3.Hide()
			self.panelPlot_5.Show()
			self.Layout()
			
		elif self.panelCSV_4.IsShown():
			self.panelCSV_4.Hide()
			self.panelPlot_5.Show()
			self.Layout()
		
		elif self.panelFinal_6.IsShown():
			self.panelFinal_6.Hide()
			self.panelPlot_5.Show()
			self.imgPanelOnOff_2.Enable(True)
			self.Layout()
		else:
			pass
        
    def evtMenuSaveCsv(self, event):
		
		''' Event -> Menu Save CSV '''
		
		if self.panelBdd_3.IsShown():
			self.panelBdd_3.Hide()
			self.panelCSV_4.Show()
			self.Layout()
			
		elif self.panelPlot_5.IsShown():
			self.panelCSV_4.Show()
			self.panelPlot_5.Hide()
			if self.imgPanelCSV_4.GetBitmapDisabled():
				self.imgPanelOnOff_2.Enable(True)
			self.Layout()
			
		elif self.panelFinal_6.IsShown():
			self.panelFinal_6.Hide()
			self.panelCSV_4.Show()
			self.imgPanelOnOff_2.Enable(True)
			self.Layout()
		else:
			pass

    def evtOpenXls(self, event):
		
		''' Event Button Abrir XLS -> Dialog escolha do XLS a analisar '''
		
		file_path = self.file_chooser.chooseFile()
		if file_path != None:
			try:

				startTime = time.time()
				read_sheet_toBdd = self.read_xls.func_Read_Xls(file_path)
				elapsedTime = time.time() - startTime

				with open("Data/testes.txt","a") as out:
					out.write('\nFunction name : %s\n' % sys._getframe().f_code.co_name)
					out.write('Time = %s\n' % str(elapsedTime))

			except:

				option_dlg = wx.MessageBox('Erro ao abrir ou ler ficheiro.', 'Erro!', wx.CANCEL | wx.OK | wx.ICON_ERROR)
				# -> INFO - 4 == OK | 16 == CANCEL
				if option_dlg == 4:
					self.evtOpenXls(event)
			else:
				self.txtPanelXls_2_4.Enable(True)
				self.txtPanelXls_2_3.SetLabel(self.file_chooser.get_file_name())
				self.imgPanelXls_2.Enable(False)
				self.imgPanelOnOff_2.Enable(True)
				self.Layout()
				showmsg = wx.MessageBox('Ficheiro aberto e lido!', 'Info', wx.OK | wx.ICON_INFORMATION)

    def evtSaveBdd(self, event):  # wxGlade: MyFrame.<event_handler>
    
		''' Event Button Gravar BDD -> Importa o XLS para a BDD  '''
		
		NAME_BDD = "Inscritos_2010-2011-bdd.db"
		insert_bdd = CLS_Contlr_Insert_Bdd()
		try:
			startTime = time.time()
			data_bdd = insert_bdd.insert_dados(self.read_xls.get_xls_to_bdd())
			elapsedTime = time.time() - startTime
			
			with open("Data/testes.txt","a") as out:
				out.write('\nFunction name : %s\n' % sys._getframe().f_code.co_name)
				out.write('Time = %s\n' % str(elapsedTime))
		except:
			option_dlg = wx.MessageBox('Erro ao gravar base de dados.', 'Erro!', wx.OK | wx.ICON_ERROR)
		else:
			self.txtPanelBdd_3_3.SetLabel(NAME_BDD)
			self.txtPanelBdd_3_4.Enable(True)
			self.imgPanelBdd_3.Enable(False)
			self.imgPanelOnOff_2.Enable(True)
			self.savecsv_m.Enable(True)
			self.viewgraph_m.Enable(True)
			lista_uni = self.stats.query_get_unidades()
			self.comboPanelPlot_5_1.Clear()
			self.comboPanelPlot_5_3.Clear()
			self.comboPanelPlot_5_1.AppendItems(lista_uni)
			self.comboPanelPlot_5_3.AppendItems(lista_uni)
			self.Layout()
			showmsg = wx.MessageBox('Base dados gravada!', 'Info', wx.OK | wx.ICON_INFORMATION)

    def evtToCsv(self, event):
		
		''' Event Button To CSV -> Query's para CSV '''
        
		startTime = time.time()
                
		lista_query1 = self.stats.query1()
		lista_query2 = self.stats.query2()
		lista_query3 = self.stats.query3()
		lista_query4 = self.stats.query4()
		try:
			csv = CLS_Contlr_Write_Csv()
			csv.statistics_to_csv(lista_query1, lista_query2, lista_query3, lista_query4)
			
			elapsedTime = time.time() - startTime
			
			with open("Data/testes.txt","a") as out:
				out.write('\nFunction name : %s\n' % sys._getframe().f_code.co_name)
				out.write('Time = %s\n' % str(elapsedTime))
		
		except:
			option_dlg = wx.MessageBox('Erro ao gravar ficheiro de estatísticas.', 'Erro!', wx.OK | wx.ICON_ERROR)
		else:
			self.imgPanelCSV_4.Enable(False)
			self.txtPanelCSV_4_5.SetLabel("\nNome do ficheiro :\n estatisticas.csv")
			self.txtPanelCSV_4_7.Enable(True)
			self.imgPanelOnOff_2.Enable(True)
			self.Layout()
			showmsg = wx.MessageBox('Ficheiro de estatísticas gravado!', 'Info', wx.OK | wx.ICON_INFORMATION)
        
    def oncombo_unidade_nivel(self, event):
		
		''' Event combo unidades organica -> Preenche a combo dos niveis '''
		startTime = time.time()
		
		unidade = self.comboPanelPlot_5_3.GetValue()
		lista_nivel = self.stats.query_get_nivel(unidade)
		self.comboPanelPlot_5_4.Clear()
		self.comboPanelPlot_5_4.AppendItems(lista_nivel)
		
		elapsedTime = time.time() - startTime
		
		with open("Data/testes.txt","a") as out:
			out.write('\nFunction name : %s\n' % sys._getframe().f_code.co_name)
			out.write('Time = %s\n' % str(elapsedTime))
    
    def oncombo_unidade_curso(self, event):
		
		''' Event ComboBox -> Ligação BDD e obtenção das escolhas '''
		
		startTime = time.time()
		        
		unidade = self.comboPanelPlot_5_1.GetValue()
		lista_cursos = self.stats.query_get_curso(unidade)
		self.comboPanelPlot_5_2.Clear()
		self.comboPanelPlot_5_2.AppendItems(lista_cursos)
		
		elapsedTime = time.time() - startTime
		
		with open("Data/testes.txt","a") as out:
			out.write('\nFunction name : %s\n' % sys._getframe().f_code.co_name)
			out.write('Time = %s\n' % str(elapsedTime))

    def ongrafico_curso(self, event):

        ''' Event Button Plot -> Imprime resultados da ComboBox '''

        startTime = time.time()

        plot_estatisticas = CLS_Contlr_App_Plot(self.stats)
        curso = self.comboPanelPlot_5_2.GetValue()
        unidade = self.comboPanelPlot_5_1.GetValue()
        plot_estatisticas.stats_query(curso, unidade)

        elapsedTime = time.time() - startTime

        with open("Data/testes.txt","a") as out:
            out.write('\nFunction name : %s\n' % sys._getframe().f_code.co_name)
            out.write('Time = %s\n' % str(elapsedTime))
        
    def ongrafico_nivel(self, event):

        ''' Event Grafico 2 -> Impressão gráfico 2 '''

        startTime = time.time()

        plot_estatisticas_nivel = CLS_Contlr_App_Plot(self.stats)
        unidade = self.comboPanelPlot_5_3.GetValue()
        nivel = self.comboPanelPlot_5_4.GetValue()
        plot_estatisticas_nivel.stats_query4(nivel, unidade)

        elapsedTime = time.time() - startTime

        with open("Data/testes.txt","a") as out:
            out.write('\nFunction name : %s\n' % sys._getframe().f_code.co_name)
            out.write('Time = %s\n' % str(elapsedTime))
    
    def oncombo_nivel(self, event):
		
		''' Event -> Mostra imagem para fazer o plot do grafico referente ao nivel '''

		self.imgPanelPlot_5_2.Enable(True)
    
    def oncombo_curso(self, event):
		
		''' Event -> Mostra imagem para fazer plot do grafico do curso '''
        
		self.imgPanelPlot_5_1.Enable(True)

    def evtInfoXls(self, event):

        ''' Event Button Abrir XLS -> Butão no painel final '''

        try:
            webbrowser.open("Data/Inscritos_2010-2011.xls")
        
        except IOError:
        
            option_dlg = wx.MessageBox('Erro ao abrir o XLS.', 'Erro!', wx.OK | wx.ICON_ERROR)
        
        event.Skip()

    def evtInfoBdd(self, event):

        ''' Event Button Abrir BDD -> Butão no painel final '''

        try:
            webbrowser.open("Data/Inscritos_2010-2011-bdd.db")
        
        except IOError:
        
            option_dlg = wx.MessageBox('Erro ao abrir a BDD.', 'Erro!', wx.OK | wx.ICON_ERROR)

        event.Skip()

    def evtInfoCsv(self, event):
        
        ''' Event Button Abrir CSV -> Butão no painel final '''

        try:
            webbrowser.open("Data/estatisticas.csv")

        except IOError:

            option_dlg = wx.MessageBox('Erro ao abrir CSV.', 'Erro!', wx.OK | wx.ICON_ERROR)

        event.Skip()

    def evtInfoTeste(self, event):
        
        ''' Event Button Abrir Testes -> Butão no painel final '''

        try:
            webbrowser.open("Data/testes.txt")

        except IOError:

            option_dlg = wx.MessageBox('Erro ao abrir testes.', 'Erro!', wx.OK | wx.ICON_ERROR)

        event.Skip()

    def evtInfoPdf(self, event):
        
        ''' Event Button Abrir PDF -> Butão no painel final '''

        try:
            webbrowser.open("Data/lp1213-6208-6311.pdf")

        except IOError:

            option_dlg = wx.MessageBox('Erro ao abrir o PDF.', 'Erro!', wx.OK | wx.ICON_ERROR)

        event.Skip()

    def evtClose(self, event):

        ''' Event -> Fecho do programa '''

        dialBox = wx.MessageDialog(self, "Deseja mesmo sair ?", "Exit", wx.OK|wx.CANCEL|wx.ICON_QUESTION)

        dialResult = dialBox.ShowModal()
        dialBox.Destroy()
        
        if dialResult == wx.ID_OK:
            self.Destroy()

        event.Skip()
    
    def evtNext(self, event):

		''' Event -> Botão passo seguinte '''
        
		if self.panelHome_1.IsShown():
			self.panelHome_1.Hide()
			self.panelXls_2.Show()
			self.imgPanelOnOff_2.Enable(False)
			self.open_m.Enable(True)
			self.Layout()
			
		elif self.panelXls_2.IsShown():
			self.panelXls_2.Hide()
			self.panelBdd_3.Show()
			self.imgPanelOnOff_2.Enable(False)
			self.savebdd_m.Enable(True)
			self.Layout()
			
		elif self.panelBdd_3.IsShown():
			self.panelBdd_3.Hide()
			self.panelCSV_4.Show()
			self.imgPanelOnOff_2.Enable(False)
			self.Layout()
			
		elif self.panelCSV_4.IsShown():
			self.panelCSV_4.Hide()
			self.panelPlot_5.Show()
			self.imgPanelOnOff_2.Enable(True)
			self.Layout()
			
		else:
			self.panelPlot_5.Hide()
			self.panelFinal_6.Show()			
			self.imgPanelOnOff_2.Enable(False)
			self.Layout()
